import logging
from datetime import datetime

from compus.models import Offline, UserCenter, MissionStatus
from celery.task import task, periodic_task
from celery.schedules import crontab

logger = logging.getLogger(__name__)


@task()
def send_mail(client, receiver, title, content, mission_id):
    logger.info("[send mail] start")
    send_result = client.cmsi.send_mail({
        "receiver": receiver,
        "title": title,
        "content": content,
    })
    logger.info("[send mail result: %s]", send_result)


@task()
def create_user(user):
    logger.info("[create_user] start")
    if not UserCenter.objects.filter(compus_user=user):  # 如果数据库中没有当前成员的数据
        compus_user = user
        kwargs = {
            "compus_user": compus_user
        }
        UserCenter.objects.create(**kwargs)
    logger.info("[create_user] end")


@periodic_task(run_every=crontab(minute='*/10'))
def mission_overtime():
    num = Offline.objects.filter(effect_time__lte=datetime.now(),
                                 mission_status=MissionStatus.EFFECT).update(mission_status=MissionStatus.EXPIRED)
    logger.info("[mission_overtime] update num of line " + str(num))
